package com.utf999.qiangmanger.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.utf999.qiangmanger.controller.permission.AuthorityAnnotation;
import com.utf999.qiangmanger.controller.permission.AuthorityScope;
import com.utf999.qiangmanger.controller.permission.PromptModeType;
import com.utf999.qiangmanger.entity.JsonEntity;

import com.utf999.qiangmanger.entity.orm.AdminUserEntity;
import com.utf999.qiangmanger.entity.orm.CompanyEntity;
import com.utf999.qiangmanger.entity.orm.OrderInfoEntity;
import com.utf999.qiangmanger.entity.orm.StoreUserGroupEntity;
import com.utf999.qiangmanger.entity.orm.StorefrontEntity;
import com.utf999.qiangmanger.exception.BizException;
import com.utf999.qiangmanger.exception.ResponseCode;
import com.utf999.qiangmanger.service.iface.ICompanyService;
import com.utf999.qiangmanger.service.iface.IOrderInfoService;
import com.utf999.qiangmanger.service.iface.IStoreUserGroupService;
import com.utf999.qiangmanger.service.iface.IStorefrontService;

/**
 * @author yinwenjie
 *
 */
@Controller
@RequestMapping(value={"/order"})
public class OrderController extends BaseController {
	
	@Autowired
	private ICompanyService companyServie;
	
	@Autowired
	private IStorefrontService storefrontService;
	
	@Autowired
	private IStoreUserGroupService storeUserGroupService;
	
	/**
	 * 
	 */
	@Autowired
	private IOrderInfoService orderInfoService;
	
	/**
	 * 日志记录
	 */
	private static Log controllerLog4j = LogFactory.getLog(OrderController.class);
	
	/**
	 * 该方法用于在店面管理员创建工单前，进行必要的数据初始化工作
	 * @param request
	 * @param response
	 * @return 如果正确，跳转进入工单创建页面
	 */
	@RequestMapping(value={"/perCreateOrder"})
	@AuthorityAnnotation(scope={AuthorityScope.StoreAdmin} , promptMode=PromptModeType.REDIRECT)
	public ModelAndView perCreateOrder(HttpServletRequest request , HttpServletResponse response) throws BizException {
		AdminUserEntity storeAdmin = (AdminUserEntity)request.getAttribute("admin");
		
		//=========查询公司信息
		CompanyEntity company = this.companyServie.queryCompanyByuserid(storeAdmin.getUid());
		request.setAttribute("company", company);
		//=========查询店面信息	
		StorefrontEntity store = this.storefrontService.queryStorefrontByuserid(storeAdmin.getUid());
		request.setAttribute("store", store);
		//=========查询当前公司下，所有可用的用户组
		List<StoreUserGroupEntity> userGroups = this.storeUserGroupService.queryStoregroupByCompanyid(company.getUid());
		request.setAttribute("userGroups", userGroups);
		
		//返回页面
		ModelAndView mv = new ModelAndView("workorder/orderCreate");
		return mv;
	}
	
	/**
	 * 超市配货任务页面进入前的数据准备
	 * @param request
	 * @param response
	 * @return 如果正确，跳转进入工单配货页面
	 */
	@RequestMapping(value={"/perPickingOrder"})
	@AuthorityAnnotation(scope={AuthorityScope.StoreAdmin , AuthorityScope.Cashier} , promptMode=PromptModeType.REDIRECT)
	public ModelAndView perPickingOrder(HttpServletRequest request , HttpServletResponse response) throws BizException {
		ModelAndView mv = new ModelAndView("workorder/orderpicking");
		return mv;
	}
	
	/**
	 * 进入“待办工单”页面前的数据准备工作
	 * @param request
	 * @param response
	 * @return
	 * @throws BizException
	 */
	@RequestMapping(value={"/perTaskOrder"})
	@AuthorityAnnotation(scope={AuthorityScope.StoreAdmin} , promptMode=PromptModeType.REDIRECT)
	public ModelAndView perTaskOrder(HttpServletRequest request , HttpServletResponse response) throws BizException {
		ModelAndView mv = new ModelAndView("workorder/ordertasklist");
		return mv;
	}
	
	/**
	 * 进入“工单核算”页面前的数据准备工作
	 * @param request
	 * @param response
	 * @return
	 * @throws BizException
	 */
	@RequestMapping(value={"/perAccountOrder"})
	@AuthorityAnnotation(scope={AuthorityScope.StoreAdmin} , promptMode=PromptModeType.REDIRECT)
	public ModelAndView perAccountOrder(HttpServletRequest request , HttpServletResponse response) throws BizException {
		ModelAndView mv = new ModelAndView("workorder/orderaccountlist");
		return mv;
	}
	
	/**
	 * 当一个工单信息录入号以后，通过这个方法添加到服务器中
	 * @param request
	 * @param response
	 * @param storeid 该工单所属的店面信息
	 * @param roomNo 对应的房间号
	 * @param orderTypeCode 工单类型编号
	 * @param duration 标准服务时间
	 * @param integral 标准积分
	 * @param fenpeiType 工单分配方式。1：抢单模式；2：指派模式
	 * @param usergroupid 抢单模式下，选定的用户组（数组，可以是多个用户组）
	 * @param zhipaiUserid 指派模式下，指派的服务人员编号
	 * @param commodityid 消费工单下，选定的商品信息编号（数组，可以是多个）
	 * @param commodityNumber 消费工单下，选定的每一种商品的购买数量（数组，可以是多个）
	 * @param remark 非消费工单下，说明的工单服务任务
	 */
	@RequestMapping(value={"/createOrder"})
	@AuthorityAnnotation(scope={AuthorityScope.StoreAdmin} , promptMode=PromptModeType.AJAX)
	public void createOrder(HttpServletRequest request , HttpServletResponse response , String storeid , String roomNo , String orderTypeCode , Integer duration , Integer integral , Integer fenpeiType , String[] usergroupid , String zhipaiUserid , String[] commodityid , Integer[] commodityNumber , String remark) {
		JsonEntity jsonEntity = new JsonEntity();
		
		try {
			this.orderInfoService.createOrder(storeid, roomNo, orderTypeCode, duration, integral, fenpeiType, usergroupid, zhipaiUserid, commodityid, commodityNumber, remark);
			jsonEntity.setResponsecode(ResponseCode.E200);
			jsonEntity.setErrorinfo("");
			jsonEntity.setData(null);
			this.writeResponseMsg(response, jsonEntity , new String[]{"orderType" , "company" , "uniqueKey"});
		} catch (BizException e) {
			controllerLog4j.error(e.getMessage(), e);
			jsonEntity.setResponsecode(e.getResponseCode());
			jsonEntity.setData("");
			jsonEntity.setErrorinfo(e.getMessage());
			this.writeResponseMsg(response, jsonEntity);
		}
	}
	
	/**
	 * 当一个指定的工单完成了配货步骤，使用该业务方法更新工单的“配货状态”，和“应付总金额”
	 * @param request
	 * @param response
	 * @param orderinfoid 指定的工单id
	 * @param totalAmount 应付总金额
	 */
	@RequestMapping(value={"/updatePickingStatus"})
	@AuthorityAnnotation(scope={AuthorityScope.StoreAdmin , AuthorityScope.Cashier} , promptMode=PromptModeType.AJAX)
	public void updatePickingStatus(HttpServletRequest request , HttpServletResponse response , String orderinfoid , Float totalAmount) {
		JsonEntity jsonEntity = new JsonEntity();
		
		try {
			this.orderInfoService.updatePickingStatus(orderinfoid, totalAmount);
			jsonEntity.setResponsecode(ResponseCode.E200);
			jsonEntity.setErrorinfo("");
			jsonEntity.setData(null);
			this.writeResponseMsg(response, jsonEntity , new String[]{""});
		} catch (BizException e) {
			controllerLog4j.error(e.getMessage(), e);
			jsonEntity.setResponsecode(e.getResponseCode());
			jsonEntity.setData("");
			jsonEntity.setErrorinfo(e.getMessage());
			this.writeResponseMsg(response, jsonEntity);
		}
	}
	
	/**
	 * 指定的工单撤回（即指定工单的假删除操作）<br>
	 * 只有当工单类型为“抢单中”、“已指派”的情况下，才能进行撤回<br>
	 * “已完成”、“已结算”的工单，是不能进行撤回的
	 * @param request
	 * @param response
	 * @param orderinfoid
	 */
	@RequestMapping(value={"/withdrawOrderInfo"})
	@AuthorityAnnotation(scope={AuthorityScope.StoreAdmin} , promptMode=PromptModeType.AJAX)
	public void withdrawOrderInfo(HttpServletRequest request , HttpServletResponse response , String orderinfoid) {
		JsonEntity jsonEntity = new JsonEntity();
		
		try {
			this.orderInfoService.withdrawOrderInfo(orderinfoid);
			jsonEntity.setResponsecode(ResponseCode.E200);
			jsonEntity.setErrorinfo("");
			jsonEntity.setData(null);
			this.writeResponseMsg(response, jsonEntity , new String[]{""});
		} catch (BizException e) {
			controllerLog4j.error(e.getMessage(), e);
			jsonEntity.setResponsecode(e.getResponseCode());
			jsonEntity.setData("");
			jsonEntity.setErrorinfo(e.getMessage());
			this.writeResponseMsg(response, jsonEntity);
		}
	}
	
	/**
	 * 对指定的工单信息，进行核算信息的存储。
	 * @param request
	 * @param response
	 * @param orderinfoid 指定的工单编号
	 * @param realIntegral 最后核算的获得积分
	 * @param realTotalAmount 最后核算的消费单实际收费金额
	 */
	@RequestMapping(value={"/saveOrderinfoAccount"})
	@AuthorityAnnotation(scope={AuthorityScope.StoreAdmin} , promptMode=PromptModeType.AJAX)
	public void saveOrderinfoAccount(HttpServletRequest request , HttpServletResponse response , String orderinfoid , Integer realIntegral , Float realTotalAmount) {
		JsonEntity jsonEntity = new JsonEntity();
		
		AdminUserEntity admin = (AdminUserEntity)request.getAttribute("admin");
		try {
			this.orderInfoService.saveOrderinfoAccount(orderinfoid, admin.getUid(), realIntegral, realTotalAmount);
			jsonEntity.setResponsecode(ResponseCode.E200);
			jsonEntity.setErrorinfo("");
			jsonEntity.setData(null);
			this.writeResponseMsg(response, jsonEntity , new String[]{""});
		} catch (BizException e) {
			controllerLog4j.error(e.getMessage(), e);
			jsonEntity.setResponsecode(e.getResponseCode());
			jsonEntity.setData("");
			jsonEntity.setErrorinfo(e.getMessage());
			this.writeResponseMsg(response, jsonEntity);
		}
	}
	
	/**
	 * 批量核算工单，注意“消费工单”不能进行批量核算。
	 * @param request
	 * @param response
	 * @param orderinfoid 指定的工单编号
	 * @param realIntegral 最后核算的获得积分
	 * @param realTotalAmount 最后核算的消费单实际收费金额
	 */
	@RequestMapping(value={"/saveOrderinfoAccounts"})
	@AuthorityAnnotation(scope={AuthorityScope.StoreAdmin} , promptMode=PromptModeType.AJAX)
	public void saveOrderinfoAccounts(HttpServletRequest request , HttpServletResponse response , String orderinfoid[] , Integer realIntegral[]) {
		JsonEntity jsonEntity = new JsonEntity();
		
		AdminUserEntity admin = (AdminUserEntity)request.getAttribute("admin");
		try {
			this.orderInfoService.saveOrderinfoAccounts(orderinfoid, admin.getUid(), realIntegral);
			jsonEntity.setResponsecode(ResponseCode.E200);
			jsonEntity.setErrorinfo("");
			jsonEntity.setData(null);
			this.writeResponseMsg(response, jsonEntity , new String[]{""});
		} catch (BizException e) {
			controllerLog4j.error(e.getMessage(), e);
			jsonEntity.setResponsecode(e.getResponseCode());
			jsonEntity.setData("");
			jsonEntity.setErrorinfo(e.getMessage());
			this.writeResponseMsg(response, jsonEntity);
		}
	}
	
	/**
	 * 该方法用于查询指定的店面下，还没有完成商品配货的“消费单”信息。<br>
	 * 这个业务过程，只能是超市收银员使用
	 * @param storefrontid 指定的店面编号
	 * @throws BizException
	 */
	@RequestMapping(value={"/queryPickingOrder"})
	@AuthorityAnnotation(scope={AuthorityScope.StoreAdmin , AuthorityScope.Cashier} , promptMode=PromptModeType.AJAX)
	public void queryPickingOrder(HttpServletRequest request , HttpServletResponse response) {
		JsonEntity jsonEntity = new JsonEntity();
		
		List<OrderInfoEntity> orderinfors = null;
		AdminUserEntity admin = (AdminUserEntity)request.getAttribute("admin");
		try {
			orderinfors = this.orderInfoService.queryPickingOrder(admin.getStorefront().getUid());
			jsonEntity.setResponsecode(ResponseCode.E200);
			jsonEntity.setErrorinfo("");
			jsonEntity.setData(orderinfors);
			this.writeResponseMsg(response, jsonEntity , new String[]{"accountAdmin","storefront" , "company" , "orderType" , "waiter" , "groups" , "orderInfo" , "commodityType" , "uniqueKey"});
		} catch (BizException e) {
			controllerLog4j.error(e.getMessage(), e);
			jsonEntity.setResponsecode(e.getResponseCode());
			jsonEntity.setData("");
			jsonEntity.setErrorinfo(e.getMessage());
			this.writeResponseMsg(response, jsonEntity);
		}
	}
	
	/**
	 * 该方法用于查询指定的店面下，还没有完成服务的“待办工单”信息
	 * @param request
	 * @param response
	 * @param orderMode 可能作为查询条件的派单方式
	 * @param orderStatus 可能作为查询条件的工单状态
	 * @param waiterCode 可能作为查询条件的服务员工号
	 * @param roomNo 可能作为查询条件的房间号
	 */
	@RequestMapping(value={"/queryTaskOrder"})
	@AuthorityAnnotation(scope={AuthorityScope.StoreAdmin , AuthorityScope.Cashier} , promptMode=PromptModeType.AJAX)
	public void queryTaskOrder(HttpServletRequest request , HttpServletResponse response , String storeid , Integer orderMode , Integer orderStatus , String waiterCode , String roomNo) {
		JsonEntity jsonEntity = new JsonEntity();
		
		List<OrderInfoEntity> orderinfors = null;
		try {
			orderinfors = this.orderInfoService.queryTaskOrder(storeid, orderMode, orderStatus, waiterCode, roomNo);
			jsonEntity.setResponsecode(ResponseCode.E200);
			jsonEntity.setErrorinfo("");
			jsonEntity.setData(orderinfors);
			this.writeResponseMsg(response, jsonEntity , new String[]{"accountAdmin","storefront", "company" , "defines" , "userGroups" , "groups" , "orderInfo" , "commodityType" , "commoditys" , "uniqueKey" , "encodePassword"});
		} catch (BizException e) {
			controllerLog4j.error(e.getMessage(), e);
			jsonEntity.setResponsecode(e.getResponseCode());
			jsonEntity.setData("");
			jsonEntity.setErrorinfo(e.getMessage());
			this.writeResponseMsg(response, jsonEntity);
		}
	}
	
	/**
	 * 该方法用于查询指定的店面下，已经完成服务等待结算的工单信息
	 * @param storefrontid 指定的店面编号
	 * @param orderMode 可能作为查询条件的派单方式
	 * @param waiterCode 可能作为查询条件的服务员工号
	 * @param roomNo 可能作为查询条件的房间号
	 */
	@RequestMapping(value={"/queryAccountOrders"})
	@AuthorityAnnotation(scope={AuthorityScope.StoreAdmin} , promptMode=PromptModeType.AJAX)
	public void queryAccountOrders(HttpServletRequest request , HttpServletResponse response , String storefrontid , Integer orderMode , String waiterCode , String roomNo) {
		JsonEntity jsonEntity = new JsonEntity();
		
		JSONArray orderinfors = null;
		try {
			orderinfors = this.orderInfoService.queryAccountOrders(storefrontid, orderMode, waiterCode, roomNo);
			jsonEntity.setResponsecode(ResponseCode.E200);
			jsonEntity.setErrorinfo("");
			jsonEntity.setData(orderinfors);
			this.writeResponseMsg(response, jsonEntity);
		} catch (BizException e) {
			controllerLog4j.error(e.getMessage(), e);
			jsonEntity.setResponsecode(e.getResponseCode());
			jsonEntity.setData("");
			jsonEntity.setErrorinfo(e.getMessage());
			this.writeResponseMsg(response, jsonEntity);
		}
	}
	
	/**
	 * 该方法用于查询指定的已经完成服务等待结算的工单信息。
	 * 包括这个工单的预结算信息
	 * @param orderinfoid 指定的工单编号信息 
	 * @throws BizException 
	 */
	@RequestMapping(value={"/queryAccountOrder"})
	@AuthorityAnnotation(scope={AuthorityScope.StoreAdmin} , promptMode=PromptModeType.AJAX)
	public void queryAccountOrder(HttpServletRequest request , HttpServletResponse response , String orderinfoid) {
		JsonEntity jsonEntity = new JsonEntity();
		
		JSONObject orderinfor = null;
		try {
			orderinfor = this.orderInfoService.queryAccountOrder(orderinfoid);
			jsonEntity.setResponsecode(ResponseCode.E200);
			jsonEntity.setErrorinfo("");
			jsonEntity.setData(orderinfor);
			this.writeResponseMsg(response, jsonEntity);
		} catch (BizException e) {
			controllerLog4j.error(e.getMessage(), e);
			jsonEntity.setResponsecode(e.getResponseCode());
			jsonEntity.setData("");
			jsonEntity.setErrorinfo(e.getMessage());
			this.writeResponseMsg(response, jsonEntity);
		}
	}
	
	/**
	 * 查询指定工单的基本信息，包括可能的工单类型、工单商品
	 * @param orderinfoid 指定的工单编号信息
	 * @return 
	 * @throws BizException
	 */
	@RequestMapping(value={"/queryOrderinfoDetails"})
	@AuthorityAnnotation(scope={AuthorityScope.StoreAdmin , AuthorityScope.SuperAdmin} , promptMode=PromptModeType.AJAX)
	public void queryOrderinfoDetails(HttpServletRequest request , HttpServletResponse response , String orderinfoid) {
		JsonEntity jsonEntity = new JsonEntity();
		
		OrderInfoEntity orderinfor = null;
		try {
			orderinfor = this.orderInfoService.queryOrderinfoDetails(orderinfoid);
			jsonEntity.setResponsecode(ResponseCode.E200);
			jsonEntity.setErrorinfo("");
			jsonEntity.setData(orderinfor);
			if(orderinfor.getOrderMode() == 1 && (orderinfor.getOrderStatus() == 1 || orderinfor.getOrderStatus() == 2)) {
				this.writeResponseMsg(response, jsonEntity , new String[]{"accountAdmin","storefront", "company" , "defines" , "userGroups" , "orderInfo" , "commodityType" , "uniqueKey" , "encodePassword"});
			} else {
				this.writeResponseMsg(response, jsonEntity , new String[]{"accountAdmin","storefront", "company" , "defines" , "groups", "userGroups" , "orderInfo" , "commodityType" , "uniqueKey" , "encodePassword"});
			}
		} catch (BizException e) {
			controllerLog4j.error(e.getMessage(), e);
			jsonEntity.setResponsecode(e.getResponseCode());
			jsonEntity.setData("");
			jsonEntity.setErrorinfo(e.getMessage());
			this.writeResponseMsg(response, jsonEntity);
		}
	}
}
